//
//  OASMSViewController.m
//  OASystem
//
//  Created by zhoupengfei on 15/11/30.
//  Copyright © 2015年 zpf. All rights reserved.
//

#import "OASMSViewController.h"
#import "HttpTools.h"
#import "SMSModel.h"
#import "SMSCell.h"
#import "AddressModel.h"
#import "UIAlertView+Blocks.h"
#import "OANewSMSViewController.h"
#import "OAMessageDetailViewController.h"
@interface OASMSViewController ()
@property(nonatomic,assign)BOOL isSearching;
@property(nonatomic,copy)NSString * searchText;
@end

@implementation OASMSViewController

- (void)viewDidLoad {
    self.isNeedRefresh = YES;
    [super viewDidLoad];
   // [self requestData];
    [self.tableView headerBeginRefreshing];
}

-(void)requestData{
    self.isSearching = NO;
    self.currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
    
    NSString * method = nil;
    if (self.vcType == SMSViewControllerType) {
        method = KMessagePage;
    }else if (self.vcType == AddressViewControllerType){
        method = KAddressListPage;
    }
    
    [HttpTools requestWithURL:KExchother arrays:array method:method success:^(id JSON) {
       
        if (weakSelf.currentPage ==1) {
            [weakSelf.contentsArray removeAllObjects];
        }
        
        if (weakSelf.vcType == SMSViewControllerType) {
            [weakSelf.contentsArray addObjectsFromArray:[SMSModel dataWithArray:JSON[@"data"]]];
        }else if (weakSelf.vcType == AddressViewControllerType){
            [weakSelf.contentsArray addObjectsFromArray:[AddressModel dataWithArray:JSON[@"data"]]];
        }
        
        weakSelf.totalNumber = [JSON[@"number"] integerValue];
        [weakSelf setupTitle];
        [weakSelf.tableView headerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
    } failure:^(NSError *error) {
        [weakSelf.tableView headerEndRefreshing];
    }];
}

-(void)setupTitle{

    UIBarButtonItem * rightItem  = nil;
    if (self.vcType == SMSViewControllerType) {
        rightItem  = [[UIBarButtonItem alloc] initWithTitle:@"新建" style:UIBarButtonItemStylePlain target:self action:@selector(createNewSMSAction)];
    }else{
        rightItem  = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
    }
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.vcType == SMSViewControllerType ? ( self.title = [NSString stringWithFormat:@"已发短信列表"]) : (self.title = [NSString stringWithFormat:@"通讯录"]);

}

-(void)requestMoreData{
    
    NSString * method = nil;
    if (self.vcType == SMSViewControllerType) {
        method = KMessagePage;
    }else if (self.vcType == AddressViewControllerType){
        if (self.isSearching) {
            method = KAdressListSearch;
        }else{
             method = KAddressListPage;
        }
       
    }
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = nil;
    
    if (self.isSearching && self.searchText.length !=0) {
        [self loadSearchData:self.searchText]; //加载搜索更多数据
    }else{
        array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    }
    __weak typeof(self) weakSelf = self;
    [HttpTools requestWithURL:KExchother arrays:array method:method success:^(id JSON) {
        
        if (self.vcType == SMSViewControllerType) {
            [self.contentsArray addObjectsFromArray:[SMSModel dataWithArray:JSON[@"data"]]];
        }else if (self.vcType == AddressViewControllerType){
            [self.contentsArray addObjectsFromArray:[AddressModel dataWithArray:JSON[@"data"]]];
        }
        weakSelf.totalNumber = [JSON[@"number"] integerValue];
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
    } failure:^(NSError *error) {
        [weakSelf.tableView footerEndRefreshing];
    }];

}

-(void)createNewSMSAction{
    
    OANewSMSViewController * smsVC = (OANewSMSViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"SMSNewVCID"];
                                       smsVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:smsVC animated:YES];
    
}

-(void)searchAction{
    [UIAlertView showWithTitle:nil message:@"请输入搜索关键字" style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确认"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                
                [self.contentsArray removeAllObjects];
                self.isSearching = YES;
                self.searchText = textField.text;
                self.currentPage = 1;
                [self loadSearchData:self.searchText];
            }
        }
        
    }];
}

-(void)loadSearchData:(NSString*)text{
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
     NSArray * array = @[@{@"Condition":text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
    [HttpTools requestWithURL:KExchother arrays:array method:KAdressListSearch success:^(id JSON) {
        if (self.vcType == AddressViewControllerType){
            [self.contentsArray addObjectsFromArray:[AddressModel dataWithArray:JSON[@"data"]]];
        }
        weakSelf.totalNumber = [JSON[@"number"] integerValue];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.contentsArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    SMSCell *cell = [tableView dequeueReusableCellWithIdentifier:@"smsIdentifier" forIndexPath:indexPath];
//    if (self.vcType == SMSViewControllerType) {
//        SMSModel * model = self.contentsArray[indexPath.row];
//        cell.titleLabel.text = model.acceptphoneuser;
//        cell.subjectLabel.text = model.subject;
//    }else if (self.vcType == AddressViewControllerType){
//        AddressModel * model = self.contentsArray[indexPath.row];
//        cell.titleLabel.text = model.rygw;
//        if (model.phone.length != 0 && model.telphone.length !=0) {
//             cell.subjectLabel.text = [NSString stringWithFormat:@"%@/%@",model.phone,model.telphone];
//        }else if (model.phone.length !=0){
//         cell.subjectLabel.text = [NSString stringWithFormat:@"%@",model.phone];
//        }else if (model.telphone.length !=0){
//             cell.subjectLabel.text = [NSString stringWithFormat:@"%@",model.telphone];
//        }else{
//            cell.subjectLabel.text = @"";
//        }
//       
//    }
//   {

    SMSCell * cell = [SMSCell cellWithTableView:tableView];
        SMSModel * model = self.contentsArray[indexPath.row];
    cell.model = model;
    return cell;
//    }
//      return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        SMSModel * model = self.contentsArray[indexPath.row];
    CGFloat height = 54;
    CGFloat  titlesize  = [OAToolBox sizebyText:model.acceptphoneuser font:14 minsWidth:60];
    
    NSString * desstring = [NSString stringWithFormat:@"%@",model.subject];
    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:60];;
    height = titlesize + dessize + 20;
    
    if (height<54) {
    return 54;
}else{
    
    
    return  height;
}
 
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.vcType == SMSViewControllerType) {
        SMSModel * model = self.contentsArray[indexPath.row];
        
        OAMessageDetailViewController * messageDetailVC = [[OAMessageDetailViewController alloc]init];
        messageDetailVC.model = model;
                                               messageDetailVC.hidesBottomBarWhenPushed = YES;

        [self.navigationController pushViewController:messageDetailVC animated:YES];
       
    }else if (self.vcType == AddressViewControllerType){
        AddressModel * model = self.contentsArray[indexPath.row];
        if (model.telphone.length !=0) {
            NSString * phone = [NSString stringWithFormat:@"%@",model.telphone];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
        }
      
    }
    
}

@end
